<template>
  <!-- 人员管理 -->
  <div class="app-container horizontal">
    <el-row :gutter="40">
      <!--部门数据 -->
      <el-col v-if="out" class="headRowClass" :span="4" :xs="24">
        <div class="head-container">
          <el-input
            v-model="deptName"
            placeholder="请输入部门名称"
            clearable
            size="small"
            prefix-icon="el-icon-search"
          />
        </div>
        <div class="head-container">
          <el-tree
            ref="tree"
            :data="deptOptions"
            :props="defaultProps"
            node-key="id"
            :expand-on-click-node="false"
            :filter-node-method="filterNode"
            :highlight-current="currentColor"
            default-expand-all
            @node-click="handleNodeClick"
          >
            <span slot-scope="{ node, data }" class="custom-tree-node">
              <span>{{ node.label }}</span>
              <span>({{ data.userCount }})</span>
            </span>
          </el-tree>
        </div>
      </el-col>
      <!-- 用户数据 -->
      <el-col :span="out === true ? 20 : 24" :xs="24" class="right-content">
        <el-col v-if="out" :span="1">
          <el-row class="treeStyle el-tree-arrow">
            <i class="el-icon-arrow-left" @click="out = false" />
          </el-row>
        </el-col>
        <el-col v-if="!out" :span="1">
          <el-row type="flex" justify="center" class="treeStyle2 el-tree-arrow">
            <i class="el-icon-arrow-right" @click="out = true" />
          </el-row>
        </el-col>
        <div class="form-container">
          <el-form
            ref="queryForm"
            :inline="true"
            label-width="80px"
            :model="filters"
          >
            <el-form-item label="人员账号" prop="loginName">
              <el-input
                v-model="filters.loginName"
                size="small"
                placeholder
                clearable
              />
            </el-form-item>
            <el-form-item label="人员类型" prop="sysUserType">
              <el-select v-model="filters.sysUserType" clearable size="small">
                <el-option
                  v-for="dict in PersonnelType"
                  :key="dict.typeNum"
                  :label="dict.typeName"
                  :value="dict.typeNum"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="手机号码" prop="phonenumber">
              <el-input
                v-model="filters.phonenumber"
                size="small"
                placeholder
                clearable
              />
            </el-form-item>
            <!-- 高级设置一栏 start -->
            <el-form-item>
              <slot name="label">
                <i
                  class="highLevelStyle"
                  :class="
                    highLevelSet === true
                      ? 'el-icon-arrow-up'
                      : 'el-icon-arrow-down'
                  "
                  @click="highLevelSet = !highLevelSet"
                />
              </slot>
            </el-form-item>
            <el-row v-if="highLevelSet">
              <el-form-item label="人员状态" prop="status">
                <el-select v-model="filters.status" clearable size="small">
                  <el-option
                    v-for="dict in statusOptions"
                    :key="dict.dictValue"
                    :label="dict.dictLabel"
                    :value="dict.dictValue"
                  />
                </el-select>
              </el-form-item>
              <el-form-item label="创建时间">
                <el-date-picker
                  v-model="dateRange"
                  size="small"
                  value-format="yyyy-MM-dd"
                  type="daterange"
                  range-separator="-"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期"
                  :clearable="false"
                />
              </el-form-item>
            </el-row>
          </el-form>
        </div>
        <!-- 高级设置一栏 end -->
        <el-row :gutter="10" class="button-wrap">
          <el-col :span="1.5">
            <el-button
              v-clickForbidden
              icon="el-icon-search"
              size="middle"
              @click="handleQuery()"
            >搜索</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              v-clickForbidden
              icon="el-icon-refresh"
              size="middle"
              @click="resetQuery()"
            >重置</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              v-hasPermi="['system:user:resetPwd']"
              icon="el-icon-refresh"
              :disabled="single"
              size="middle"
              @click="passwordReset"
            >密码重置</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              v-hasPermi="['system:user:add']"
              icon="el-icon-plus"
              size="middle"
              @click="handleAdd()"
            >新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              v-hasPermi="['system:sysApplyRecord:list']"
              icon="el-icon-plus"
              size="middle"
              @click="handleAddRecord()"
            >添加记录</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              v-hasPermi="['system:sysApplyRecord:listByEnterprise']"
              icon="el-icon-tickets"
              size="middle"
              @click="handleApplyuser()"
            >人员审核</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              v-hasPermi="['system:user:edit']"
              icon="el-icon-edit"
              size="middle"
              :disabled="single"
              @click="handleUpdate()"
            >修改</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              v-hasPermi="['system:user:remove']"
              icon="el-icon-delete"
              size="middle"
              :disabled="single"
              @click="handleDelete()"
            >删除</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              v-hasPermi="['system:user:detail']"
              icon="el-icon-zoom-in"
              size="middle"
              :disabled="single"
              @click="handleDetail"
            >详情</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              v-hasPermi="['system:user:edit']"
              size="middle"
              :icon="
                disabledStatus === '1' ? 'el-icon-star-on' : 'el-icon-star-off'
              "
              :disabled="isStop"
              @click="handleStatusChange"
            >
              {{ disabledContent }}
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              v-hasPermi="['system:user:accountUserDimission']"
              icon="el-icon-folder-delete"
              size="middle"
              :disabled="isQuit"
              @click="handleQuit"
            >离职</el-button>
          </el-col>
          <el-col :span="2.5">
            <el-button
              v-hasPermi="['system:user:edit']"
              size="middle"
              icon="el-icon-connection"
              :disabled="single"
              @click="handleMenuAndScope()"
            >菜单和数据权限分配</el-button>
          </el-col>
        </el-row>
        <!-- 表格展示start -->
        <el-table
          ref="multipleTable"
          v-loading="loading"
          :data="sysUserData"
          :row-style="rowClass"
          style="width: 100%;"
          stripe
          class="table-list"
          :class="
            highLevelSet === true
              ? needTagsView === true
                ? 'el-body-page-roll-tag-height'
                : 'el-body-page-roll-height'
              : needTagsView === true
                ? 'el-body-page-roll-tag'
                : 'el-body-page-roll'
          "
          @selection-change="handleSelectionChange"
          @row-click="rowChecked"
        >
          <el-table-column type="selection" width="38" align="center" />
          <el-table-column
            type="index"
            label="序号"
            width="50"
            align="center"
          />
          <el-table-column
            prop="loginName"
            label="人员账号"
            min-width="80"
            align="center"
            :show-overflow-tooltip="true"
          />
          <el-table-column
            prop="userName"
            label="人员昵称"
            min-width="80"
            align="center"
            :show-overflow-tooltip="true"
          />
          <el-table-column
            prop="sysUserType"
            label="类型"
            min-width="80"
            align="center"
            :show-overflow-tooltip="true"
            :formatter="(row) => formatterPersonSupperType(row,'sysUserType')"
          />
          <el-table-column
            prop="dept.deptName"
            label="部门"
            min-width="80"
            align="center"
            :show-overflow-tooltip="true"
          >
            <template slot-scope="scope">
              <span v-if="scope.row.dept !== undefined">{{
                scope.row.dept.deptName
              }}</span>
            </template>
          </el-table-column>
          <el-table-column
            prop="phonenumber"
            label="手机号码"
            min-width="60"
            align="center"
            :show-overflow-tooltip="true"
          />
          <el-table-column
            prop="status"
            min-width="80"
            label="状态"
            align="center"
            :formatter="statusFormat"
          />
        </el-table>
        <!-- 表格展示end-->
        <!-- 分页-->
        <pagination
          :total="total"
          :page.sync="filters.pageNum"
          :limit.sync="filters.pageSize"
          @pagination="getList"
        />
      </el-col>
    </el-row>
    <!-- 添加页面start -->
    <el-dialog
      v-dialogDrag
      :title="dialogTitle"
      :close-on-click-modal="false"
      :visible.sync="dialogVisible"
      class="dialogStyleMiddle"
      :before-close="cancel"
    >
      <el-tabs v-model="activeName">
        <el-tab-pane :label="dialogTitle" name="first">
          <el-form
            v-if="dialogVisible"
            ref="addSysUserForm"
            :model="sysUser"
            :rules="rules"
            label-width="80px"
          >
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="归属部门" prop="deptId">
                  <treeselect
                    v-model="sysUser.deptId"
                    :options="deptOptionsAll"
                    placeholder="请选择归属部门"
                    size="medium"
                    no-options-text="暂无数据"
                    :normalizer="normalizer"
                    @input="updateDeptType"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="岗位分类" prop="postIds">
                  <el-select
                    v-model="sysUser.postIds"
                    multiple
                    filterable
                    default-first-option
                    placeholder="请选择岗位"
                    size="medium"
                  >
                    <el-option
                      v-for="item in postOptions"
                      :key="item.postId"
                      :label="item.postName"
                      :value="item.postId"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="姓名" prop="userName">
                  <label slot="label" v-html="`姓&emsp;&emsp;名`" />
                  <el-input
                    v-model="sysUser.userName"
                    placeholder="请输入姓名"
                    size="medium"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="登录账号" prop="loginName">
                  <el-input
                    v-model="sysUser.loginName"
                    placeholder="请输入登录账号"
                    auto-complete="off"
                    :disabled="sysUser.userId === '' ? false : true"
                    size="medium"
                  />
                </el-form-item>
              </el-col>
              <el-col v-if="sysUser.userId == ''" :span="12">
                <el-form-item label="人员密码" prop="password">
                  <el-input
                    v-model="sysUser.password"
                    placeholder
                    type="password"
                    autocomplete="new-password"
                    size="medium"
                  />
                </el-form-item>
              </el-col>
              <el-col v-if="sysUser.userId == ''" :span="12">
                <el-form-item label="确认密码" prop="Confirmpassword">
                  <el-input
                    v-model="sysUser.Confirmpassword"
                    placeholder
                    type="password"
                    size="medium"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="手机号码" prop="phonenumber">
                  <el-input
                    v-model="sysUser.phonenumber"
                    placeholder="请输入手机号"
                    size="medium"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="人员性别" prop="sex">
                  <el-radio-group v-model="sysUser.sex" size="medium">
                    <el-radio
                      v-for="dict in sexOptions"
                      :key="dict.dictValue"
                      :label="dict.dictValue"
                      size="medium"
                    >
                      {{ dict.dictLabel }}
                    </el-radio>
                  </el-radio-group>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="电子邮箱" prop="email">
                  <el-input
                    v-model="sysUser.email"
                    placeholder="请输入邮箱"
                    size="medium"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="角色" prop="roleIds" size="medium">
                  <label slot="label" v-html="`角&emsp;&emsp;色`" />
                  <el-select
                    v-model="sysUser.roleIds"
                    multiple
                    filterable
                    default-first-option
                    placeholder="请选择角色"
                    size="medium"
                  >
                    <el-option
                      v-for="item in roleOptions"
                      :key="item.roleId"
                      :label="item.roleName"
                      :value="item.roleId"
                      size="medium"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="权限范围" prop="dataScope" size="medium">
                  <el-select v-model="sysUser.dataScope">
                    <el-option
                      v-for="dict in dataScopeOptions"
                      :key="dict.dictValue"
                      size="medium"
                      :label="dict.dictLabel"
                      :value="dict.dictValue"
                    />
                  </el-select>
                  <div style="color:red">该人员拥有菜单的默认数据权限</div>
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="备注信息" prop="remark">
                  <el-input
                    v-model="sysUser.remark"
                    type="textarea"
                    size="medium"
                  />
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </el-tab-pane>
        <el-tab-pane
          v-if="dialogTitle !== '修改人员'"
          label="搜索添加人员"
          name="second"
        >
          <el-row>
            <el-form
              ref="userForm"
              label-width="80px"
              :model="userForm"
              :rules="userRules"
            >
              <el-row :gutter="20">
                <el-col :span="12">
                  <el-form-item label="归属部门" prop="deptId">
                    <treeselect
                      v-model="userForm.deptId"
                      :options="deptOptionsAll"
                      placeholder="请选择归属部门"
                      size="medium"
                      no-options-text="暂无数据"
                      :normalizer="normalizer"
                      @input="updateDeptType"
                    />
                    <!-- clear-value-text="暂无数据11" -->
                    <!-- :append-to-body="true"
                  :disable-branch-nodes="true" -->
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="岗位分类" prop="postIds">
                    <el-select
                      v-model="userForm.postIds"
                      multiple
                      filterable
                      default-first-option
                      placeholder="请选择岗位"
                      size="medium"
                    >
                      <el-option
                        v-for="item in postOptions"
                        :key="item.postId"
                        :label="item.postName"
                        :value="item.postId"
                      />
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="角色" prop="roleIds" size="medium">
                    <label slot="label" v-html="`角&emsp;&emsp;色`" />
                    <el-select
                      v-model="userForm.roleIds"
                      multiple
                      filterable
                      default-first-option
                      placeholder="请选择角色"
                      size="medium"
                    >
                      <el-option
                        v-for="item in roleOptions"
                        :key="item.roleId"
                        :label="item.roleName"
                        :value="item.roleId"
                        size="medium"
                      />
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="权限范围" prop="dataScope" size="medium">
                    <el-select v-model="userForm.dataScope">
                      <el-option
                        v-for="dict in dataScopeOptions"
                        :key="dict.dictValue"
                        size="medium"
                        :label="dict.dictLabel"
                        :value="dict.dictValue"
                      />
                    </el-select>
                    <div style="color:red">该人员拥有菜单的默认数据权限</div>
                  </el-form-item>
                </el-col>
                <el-col :span="24">
                  <el-form-item label="备注信息" prop="remark">
                    <el-input
                      v-model="userForm.remark"
                      type="textarea"
                      size="medium"
                    />
                  </el-form-item>
                </el-col>
              </el-row>
            </el-form>
            <el-form
              ref="searchForm"
              :inline="true"
              :model="queryUser"
            >
              <el-form-item label="用户名称" prop="name">
                <el-input
                  v-model="queryUser.name"
                  size="medium"
                  class="serach-person"
                  placeholder="请输入用户名称"
                />
              </el-form-item>
              <el-form-item label="手机号" prop="phone">
                <el-input
                  v-model="queryUser.phone"
                  size="medium"
                  class="serach-person"
                  placeholder="请输入手机号"
                />
                <el-button
                  size="medium"
                  type="primary"
                  @click="searchPersonnel"
                >搜索</el-button>
              </el-form-item>
            </el-form>
            <el-table
              ref="userTable"
              :data="tableData"
              style="width: 100%;"
              stripe
              class="table-list"
              @selection-change="selectUserChange"
              @row-click="rowUserClick"
            >
              <el-table-column type="selection" width="38" align="center" />
              <el-table-column
                prop="name"
                label="用户名称"
                min-width="150"
                align="center"
              />
              <el-table-column
                prop="surveyType"
                label="用户类型"
                min-width="130"
                align="center"
                :formatter="(row) => formatterPersonSupperType(row,'surveyType')"
              />
              <el-table-column
                prop="idCard"
                label="身份证号"
                width="180"
                align="center"
              />
              <el-table-column
                prop="phone"
                label="手机号码"
                min-width="130"
                align="center"
              />
            </el-table>
          </el-row>
        </el-tab-pane>
      </el-tabs>

      <span slot="footer" class="dialog-footer">
        <el-button size="medium" @click="cancel">取 消</el-button>
        <el-button
          size="medium"
          type="primary"
          :disabled="btnDisabled"
          @click="submitForm"
        >保 存</el-button>
      </span>
    </el-dialog>
    <!-- 添加页面end-->
    <!-- 人员兼职部门 start -->
    <user-part-dept v-if="userPartDeptVisible" ref="userPartDept" />
    <!-- 人员分配菜单数据权限-->
    <user-menu-data v-if="userMenuDataVisible" ref="userMenuData" />
    <!-- 导出对话框 -->
    <Export ref="export" @parentGetList="parentGetList" />
    <!-- 导入对话框 -->
    <ToLead ref="toLead" />
    <detail ref="detail" />
  </div>
</template>

<script>
import { sysAccountPersonnel } from '@/api/system/profile'
import { personalAddEnterprise } from '@/api/common/approvalReminder'
import { personTypeListNoPermission } from '@/api/superviseBaseInfo/typeManage/personnelType'
// 树型选择引入
import Treeselect from '@riophae/vue-treeselect'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
// 人员兼职部门弹框引入
import UserPartDept from '@/views/system/user/components/UserPartDept/index'

// 人员分配菜单数据权限
import UserMenuData from '@/components/System/User/UserMenuDataScope'
// 引入高级设置一栏
// import HighLevelSetting from '@/components/HighLevelSetting'
// 引入导出对话框
import Export from './components/Export/index'
// 引入导入对话框
import ToLead from './components/ToLead/index'
import Detail from './components/Detail'
// 引入封装好的接口
import {
  checkLoginNameUnique,
  listUser,
  updateUser,
  updateUserStatus,
  addUser,
  delUser,
  getUserByUserId,
  checkPhoneUnique,
  resetPswd,
  updateQuitStatus
} from '@/api/system/user'
// checkEmailUnique,
// 引入角色 中查询list方法
import { listRoleAll } from '@/api/system/role'
import { listPostAll } from '@/api/system/post'
import {
  selectAllCompanyDeptTree,
  getDeptByDeptId,
  getDeptTree
} from '@/api/system/dept'
import { getDicts } from '@/api/system-tool/dict/data'
import { mapState } from 'vuex'
export default {
  // eslint-disable-next-line vue/no-unused-components
  components: {
    Treeselect,
    'user-part-dept': UserPartDept,
    UserMenuData,
    Export,
    ToLead,
    Detail
  },
  data() {
    // form表单自定义查重验证
    const validLoginName = (rule, value, callback) => {
      const reg = /^[A-Za-z0-9]+$/
      if (!value) {
        return callback(new Error('登录账号不能为空'))
      } else if (!reg.test(value) && value !== '') {
        return callback(new Error('登录账号必须为英文和数字'))
      } else if (value.length < 2) {
        return callback(new Error('登录账号长度不能小于2位'))
      } else if (value.length > 20) {
        return callback(new Error('登录账号长度不能大于20位'))
      } else {
        const userId = this.sysUser.userId
        const loginName = value
        checkLoginNameUnique(userId, loginName).then(resp => {
          if (resp.data === '1') {
            return callback(new Error('登录账号已经存在'))
          } else {
            callback()
          }
        })
      }
    }
    const validPassword = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('密码不能为空'))
      } else if (value.length < 6) {
        return callback(new Error('密码长度不能小于6位'))
      } else if (value.length > 20) {
        return callback(new Error('密码长度不能大于20位'))
      } else {
        callback()
      }
    }
    const passwordAlike = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('确认密码不能为空'))
      } else if (this.sysUser.password !== value) {
        return callback(new Error('确认密码与登录密码不一致'))
      } else {
        callback()
      }
    }
    // 电话号码查重验证
    const validPhoneNumber = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('手机号码不能为空'))
      } else {
        const userId = this.sysUser.userId
        const phone = value
        checkPhoneUnique(userId, phone).then(resp => {
          if (resp.data === '1') {
            return callback(new Error('该手机已被注册，请重新输入！'))
          } else {
            callback()
          }
        })
      }
    }
    // 查看选择的归属部门是不是分公司
    const validSubCompany = (rule, value, callback) => {
      if (this.deptType === '2') {
        return callback(new Error('所属部门不能选择分公司'))
      } else if (this.deptType === '0') {
        return callback(new Error('所属部门不能选择公司'))
      } else {
        callback()
      }
    }
    return {
      deptType: '',
      // 浏览器宽度
      clientWidth: `${document.documentElement.clientWidth}`,
      // 树高亮
      currentColor: false,
      tooltipContent: '隐藏',
      // 高级设置显示隐藏
      highLevelSet: false,
      // 对话框确定按钮
      btnDisabled: false,
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 左侧树状图状态
      out: true,
      // 导入允许的最大的个数
      limitNumber: 1,
      //  导入的文件暂存
      fileTemp: undefined,
      fileListUpload: [],
      sysUserData: [],
      // 部门名称
      deptName: undefined,
      // 部门树选项
      deptOptions: undefined,
      deptOptionsAll: [],
      defaultProps: {
        children: 'children',
        label: 'label'
      },
      // 选中表格对话框的存储的值
      multipleSelection: [],
      // 高亮样式
      selectRow: [],
      // 启用/停用显示状态
      disabledStatus: '0',
      disabledContent: '停用',
      // 查询参数
      filters: {
        pageNum: 1,
        pageSize: this.fristPageSize,
        deptId: '',
        loginName: '',
        userName: '',
        phonenumber: '',
        status: '0',
        email: '',
        roleIds: [],
        postIds: [],
        dataObjType: 'SysUser',
        sysUserType: ''
      },
      // 人员类型
      PersonnelType: [{ typeNum: '', typeName: '全部' }],
      // 性别信息
      sexOptions: [],
      // 状态信息
      statusOptions: [],
      // 日期范围
      dateRange: [],
      // 分页总条数
      total: 0,
      // 添加编辑弹框页面属性定义
      // 弹出的对话框的标题
      dialogTitle: '',
      // 对话框是否弹出显示
      dialogVisible: false,
      // 表格加载是否显示等待图标
      loading: false,
      sysUser: {
        userId: '',
        loginName: '',
        deptId: undefined,
        phonenumber: '',
        email: '',
        userName: '',
        password: '',
        Confirmpassword: '',
        sex: '0',
        status: '0',
        roleIds: [],
        postIds: [],
        remark: '',
        dataScope: ''
      },
      normalizer(node) {
        return {
          id: node.deptId,
          label: node.deptName,
          children: node.children
        }
      },
      // 角色选择
      roleOptions: [],
      // 岗位选择
      postOptions: [],
      // 数据范围选项 1：全部数据权限3：本部门数据权限 4：本部门及以下数据权限 5：仅本人数据权限
      dataScopeOptions: [],
      // from表单验证
      rules: {
        loginName: [
          // 自定义验证方式
          { required: true, validator: validLoginName, trigger: 'blur' }
        ],
        userName: [
          { required: true, message: '人员名称不能为空', trigger: 'blur' }
        ],
        nickName: [
          { required: true, message: '人员昵称不能为空', trigger: 'blur' }
        ],
        deptId: [
          { required: true, message: '归属部门不能为空', trigger: 'blur' },
          { required: true, validator: validSubCompany, trigger: 'blur' }
        ],
        password: [
          { required: true, validator: validPassword, trigger: 'blur' }
        ],
        Confirmpassword: [
          { required: true, validator: passwordAlike, trigger: 'blur' }
        ],
        // email: [
        //   {
        //     required: true,
        //     type: 'email',
        //     message: "'请输入正确的邮箱地址",
        //     trigger: ['blur', 'change']
        //   },
        //   { required: true, validator: validLoginEmail, trigger: 'blur' }
        // ],
        phonenumber: [
          {
            required: true,
            pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
            message: '请输入正确的手机号码',
            trigger: 'blur'
          },
          { required: true, validator: validPhoneNumber, trigger: 'blur' }
        ],
        dataScope: [
          { required: true, message: '权限范围是必选项', trigger: 'blur' }
        ]
      },
      /** 人员兼职部门 start */
      userPartDeptVisible: false,
      /** 人员分配菜单和数据权限 */
      userMenuDataVisible: false,
      // 选中人员
      userSelection: [],
      // 人员选中行
      selectUserRow: [],
      // 搜索添加人员过滤条件
      queryUser: {
        name: '',
        phone: ''
      },
      // 人员数据
      tableData: [],
      // 新增tab切换
      activeName: 'first',
      userForm: {
        postIds: [], // 岗位分类
        roleIds: [], // 角色id
        dataScope: '', // 权限范围
        remark: '', //  备注
        deptId: undefined // 归属部门
      },
      // 搜索添加验证
      userRules: {
        deptId: [
          { required: true, message: '归属部门不能为空', trigger: 'blur' },
          { required: true, validator: validSubCompany, trigger: 'blur' }
        ],
        dataScope: [
          { required: true, message: '权限范围是必选项', trigger: 'blur' }
        ]
      }
    }
  },
  computed: {
    ...mapState({
      needTagsView: state => state.settings.tagsView,
      userInfo: state => state.user.userInfo
    }),
    // 高级搜索显示隐藏
    handleTagShow() {
      return this.highLevelSet
    },
    isQuit() {
      const m = this.multipleSelection
      return m.length !== 1 || !m[0].sysUserType
    },
    isStop() {
      const m = this.multipleSelection
      return m.length !== 1 || m[0].userType !== '00'
    }
  },
  watch: {
    // 根据名称筛选部门树
    deptName(val) {
      this.$refs.tree.filter(val)
    },
    // 监听浏览器宽度
    clientWidth(val) {
      if (!this.timer) {
        this.clientWidth = val
        this.timer = true
        setTimeout(() => {
          this.timer = false
        }, 500)
      }
    }
  },
  created() {
    this.listPersonSupperType()
  },
  mounted() {
    this.getList()
    this.selectDeptTree()
    this.selectRoleOptions()
    this.selectPostOptions()
    // 人员性别
    this.getDicts('sys_user_sex').then(res => {
      this.sexOptions = res.data.rows
    })
    // 人员状态信息
    getDicts('sys_normal_disable').then(res => {
      this.statusOptions = res.data.rows
    })
    // 角色数据权限
    this.getDicts('role_data_scope').then(res => {
      this.dataScopeOptions = res.data.rows
    })
    window.onresize = () => {
      return (() => {
        this.clientWidth = `${document.documentElement.clientWidth}`
      })()
    }
    if (this.$route.query.id) {
      this.handleDetailRouter()
    }
  },
  methods: {
    // 部门树变化
    updateDeptType(val) {
      if (val) this.getDeptType(val)
    },
    handleQuit() {
      const userId = this.multipleSelection[0].userId
      this.$confirm('确认要离职吗', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        updateQuitStatus({ status: 1, userId }).then(res => {
          if (res.data) {
            this.msgSuccess('离职成功!')
          }
        })
      }).catch(() => {
        this.msgWarning('已取消')
      })
    },
    // 获取公司类型
    getDeptType(value) {
      getDeptByDeptId(value).then(resp => {
        if (resp) {
          this.deptType = resp.data.deptType
        }
      })
    },
    // 获取人员类型
    async  listPersonSupperType() {
      const { data: { rows }} = await personTypeListNoPermission()
      this.PersonnelType = rows
    },
    // 回显人员类型
    formatterPersonSupperType(row, keyName) {
      if (keyName in row) {
        const index = this.PersonnelType.findIndex(item => {
          return item.typeNum === row[keyName]
        })
        return index !== -1 ? this.PersonnelType[index].typeName : '内部人员'
      }
    },

    // 选择人员改变
    selectUserChange(val) {
      if (JSON.stringify(val[0]) === '{}') {
        this.$refs.userTable.clearSelection()
        val = []
      }
      this.selectUserRow = []
      this.userSelection = val
      if (this.userSelection.length > 0) {
        this.userSelection.forEach((item, index) => {
          this.selectUserRow.push(this.tableData.indexOf(item))
        })
      }
      if (val.length > 1) {
        this.$refs.userTable.clearSelection()
        this.$refs.userTable.toggleRowSelection(val.pop())
      }
    },
    // 点击当前行
    rowUserClick(row) {
      const selectData = this.userSelection
      this.$refs.userTable.clearSelection()
      if (selectData.length === 1) {
        selectData.forEach(item => {
          if (item === row) {
            this.$refs.userTable.toggleRowSelection(row, false)
          } else {
            this.$refs.userTable.toggleRowSelection(row, true)
          }
        })
      } else {
        this.$refs.userTable.toggleRowSelection(row, true)
      }
    },
    // 搜索添加人员
    async searchPersonnel() {
      this.tableData = []
      const { data } = await sysAccountPersonnel(this.queryUser)
      if (data.length === 0) this.msgWarning('未搜索到相关人员')
      this.tableData = data
    },
    // 获取高级设置中子组件传递的数据
    getValueFromChild(data) {
      this.highLevelQueryParams = data
    },
    // 人员性别字典翻译
    sexFormat(row, column) {
      return this.selectDictLabel(this.sexOptions, row.sex)
    },
    // 人员状态字典翻译
    statusFormat(row, column) {
      return this.selectDictLabel(this.statusOptions, row.status)
    },
    // 单击每行时每行的复选框选中
    rowChecked(row) {
      const selectData = this.multipleSelection
      this.$refs.multipleTable.clearSelection()
      if (selectData.length === 1) {
        selectData.forEach(item => {
          // 判断 如果当前的一行被勾选, 再次点击的时候就会取消选中
          if (item === row) {
            this.$refs.multipleTable.toggleRowSelection(row, false)
          } else {
            this.$refs.multipleTable.toggleRowSelection(row, true)
          }
        })
      } else {
        this.$refs.multipleTable.toggleRowSelection(row, true)
      }
    },
    // 导出
    handleExport() {
      const { loginName, userName, phonenumber, status } = this.filters
      const form = { loginName, userName, phonenumber, status, dateRange: this.dateRange }
      this.$refs.export.openExport(form)
    },
    // 导入按钮
    handleToLead() {
      this.$refs.toLead.openToLead()
    },
    // 部门筛选节点
    filterNode(value, data) {
      if (!value) return true
      return data.label.indexOf(value) !== -1
    },
    // 人员状态修改
    handleStatusChange() {
      const row = this.multipleSelection[0]
      const text = row.status === '0' ? '停用' : '启用'
      this.$confirm('确认要' + text + '' + row.userName + '人员吗?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async() => {
          if (row.status === '0') {
            row.status = '1'
          } else {
            row.status = '0'
          }
          const formdata = {
            userId: row.userId,
            status: row.status
          }
          updateUserStatus(formdata).then(resp => {
            if (resp) {
              this.getList()
              this.msgSuccess('操作成功！')
              this.selectDeptTree()
            } else {
              this.msgError(resp.message)
            }
          })
        })
        .catch(() => {})
    },
    // 部门节点单击事件
    handleNodeClick(data) {
      this.filters.deptId = data.id
      this.handleQuery()
      this.$nextTick(() => {
        // 使树筛选时选中的节点高亮显示
        this.currentColor = true
        this.$refs.tree.setCurrentKey(data.id)
      })
    },
    // 点击表格前面选框时触发的事件
    handleSelectionChange(val) {
      if (JSON.stringify(val[0]) === '{}') {
        this.$refs.multipleTable.clearSelection()
        val = []
      }
      // 0代表正常状态，1代表停用状态
      this.multipleSelection = val
      if (
        this.multipleSelection.length === 1 &&
        // eslint-disable-next-line no-prototype-builtins
        this.multipleSelection[0].hasOwnProperty('userId')
      ) {
        this.single = false
        this.disabledStatus = this.multipleSelection[0].status
        if (this.disabledStatus === '0') {
          this.disabledContent = '停用'
        } else {
          this.disabledContent = '启用'
        }
      } else {
        this.single = true
      }
      this.selectRow = []
      if (this.multipleSelection.length > 0) {
        this.multipleSelection.forEach((item, index) => {
          this.selectRow.push(this.sysUserData.indexOf(item))
        })
      }
      if (val.length > 1) {
        this.$refs.multipleTable.clearSelection()
        this.$refs.multipleTable.toggleRowSelection(val.pop())
      }
    },
    // 高亮样式
    rowClass({ row, rowIndex }) {
      if (this.selectRow.includes(rowIndex)) {
        return { 'background-color': 'rgba(185,221,249,.75)' }
      }
    },
    getList() {
      this.loading = true
      listUser(this.changeDateRange(this.filters, this.dateRange)).then(
        resp => {
          this.loading = false
          if (resp) {
            this.sysUserData = resp.data.rows
            this.total = resp.data.total
            // this.addTaleData()
          } else {
            this.msgError(resp.message)
          }
        }
      )
    },
    // list表格填充空白行
    addTaleData() {
      if (this.sysUserData.length < this.fristPageSize) {
        const arr = {}
        this.sysUserData.push(arr)
        this.addTaleData()
      }
    },
    parentGetList() {
      this.getList()
    },
    handleDetailRouter() {
      this.$refs.detail.handleDetail(this.$route.query.id)
    },
    handleDetail() {
      this.$refs.detail.handleDetail(this.multipleSelection[0].userId)
    },
    // 表单重置
    emptySysUser() {
      this.sysUser.userId = ''
      this.sysUser.phonenumber = ''
      this.sysUser.status = '0'
      this.sysUser.enterpriseId = ''
      this.sysUser.password = ''
      this.resetForm('addSysUserForm')
    },
    // 搜索方法
    handleQuery() {
      this.filters.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm('queryForm')
      this.filters.sex = ''
      this.filters.status = '0'
      this.dateRange = []
      this.handleQuery()
    },
    // 查找角色表的所有信息
    selectRoleOptions() {
      listRoleAll().then(resp => {
        if (resp) {
          this.roleOptions = resp.data.rows
        } else {
          this.msgError(resp.message)
        }
      })
    },
    // 查找岗位表的所有信息
    selectPostOptions() {
      listPostAll().then(resp => {
        if (resp) {
          this.postOptions = resp.data.rows
        } else {
          this.msgError(resp.message)
        }
      })
    },
    // 部门选择树列表
    selectDeptTree() {
      selectAllCompanyDeptTree().then(resp => {
        if (resp) {
          if (resp.data !== null) {
            this.deptOptionsAll = this.deleteChildren(resp.data)
          }
        }
      })
      getDeptTree({ dataObjType: 'SysUser' }).then(resp => {
        if (resp) {
          this.deptOptions = resp.data
        }
      })
    },
    // 密码重置功能
    passwordReset() {
      this.$confirm('您确定要重置密码吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          const userId = this.multipleSelection[0].userId
          resetPswd(userId).then(resp => {
            if (resp) {
              this.msgSuccess('密码重置成功! 新密码为 111111')
            } else {
              this.msgError(resp.message)
            }
          })
        })
        .catch(() => {})
    },
    // 新增方法
    handleAdd() {
      // 清空人员
      this.emptySysUser()
      this.dialogTitle = '新增人员'
      this.dialogVisible = true
      this.selectRoleOptions()
      this.selectPostOptions()
    },
    // 邀请记录
    handleAddRecord() {
      this.$router.push({
        path: '/resourceManage/userRecord'
      })
    },
    // 申请加入企业的人员
    handleApplyuser() {
      this.$router.push({
        path: '/resourceManage/userApply'
      })
    },
    // 更新方法
    handleUpdate() {
      // 获取选中行的id
      const child = this.multipleSelection
      this.emptySysUser()
      this.dialogTitle = '修改人员'
      this.dialogVisible = true
      // 主键
      const id = child[0].userId
      // 根据id查找这条的内容
      getUserByUserId(id).then(res => {
        if (res) {
          const { user, roles, posts } = res.data
          // 选择的角色
          const someRoles = user.roles
          // 全部角色
          // eslint-disable-next-line no-array-constructor
          const roleArray = new Array()
          for (let k = 0; k < someRoles.length; k++) {
            roleArray.push(someRoles[k].roleId)
          }
          this.sysUser.roleIds = roleArray
          this.roleOptions = roles
          // eslint-disable-next-line no-array-constructor
          const postArray = new Array()
          for (let j = 0; j < posts.length; j++) {
            if (posts[j].flag) {
              postArray.push(posts[j].postId)
            }
          }
          this.sysUser.postIds = postArray
          this.postOptions = posts
          const { userId, deptId, loginName, phonenumber, email, userName,
            password, sex, enterpriseId, dataScope, remark, fileId } = user
          this.sysUser = { ...this.sysUser, userId, deptId, loginName, phonenumber, email, userName,
            password, sex, enterpriseId, dataScope, remark, fileId, reserved1: fileId }
        } else {
          this.msgError(res.message)
        }
      })
    },

    // 弹框取消按钮
    cancel() {
      this.dialogVisible = false
      this.btnDisabled = false
      this.activeName = 'first'
      this.emptySysUser()
      this.resetForm('searchForm')
      this.resetForm('userForm')
      this.userSelection = []
      this.tableData = []
    },
    // 弹框确认按钮
    submitForm() {
      if (this.activeName === 'second') {
        this.$refs['userForm'].validate(async(valid) => {
          if (valid) {
            if (this.userSelection.length === 0) {
              return this.msgWarning('请先选择人员')
            }
            const data = {
              enterpriseId: this.userInfo.enterpriseId,
              accountType: 1,
              applyType: 1,
              accountId: this.userSelection[0].id,
              accountNum: this.userSelection[0].phone,
              userJson: JSON.stringify({ ...this.userSelection[0], ...this.userForm })
            }
            await personalAddEnterprise(data)
            this.loading = false
            this.selectDeptTree()
            this.getList()
            this.cancel()
            this.msgSuccess('消息发送成功，待用户同意！')
          }
        })
        return
      }
      this.$refs['addSysUserForm'].validate(valid => {
        if (valid) {
          this.btnDisabled = true
          if (this.sysUser.userId) {
            // 更新
            this.loading = true
            updateUser(this.sysUser).then(resp => {
              this.loading = false
              if (resp) {
                this.cancel()
                this.msgSuccess('修改成功')
                // 部门选择树列表
                this.selectDeptTree()
                this.getList()
              } else {
                this.msgError(resp.message)
                this.btnDisabled = false
              }
              this.activeName = 'first'
            })
          } else {
            this.loading = true
            addUser(this.sysUser).then(resp => {
              this.loading = false
              if (resp) {
                this.selectDeptTree()
                this.getList()
                this.cancel()
              } else {
                this.msgError(resp.message)
                this.btnDisabled = false
              }
              this.activeName = 'first'
            })
          }
        }
      })
    },

    handleDelete() {
      // 获取选中行的id
      const child = this.multipleSelection
      if (child.length === 0) {
        this.msgInfo('请选择需要删除的项!')
      } else {
        this.$confirm('确认要删除人员吗?', '警告', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
          .then(async() => {
            this.loading = true
            let ids = ''
            for (let i = 0; i < child.length; i++) {
              ids += child[i].userId + ','
            }
            // 去掉最后一个逗号
            if (ids.length > 0) {
              ids = ids.substr(0, ids.length - 1)
            }
            delUser(ids).then(resp => {
              this.loading = false
              if (resp) {
                this.msgSuccess('删除成功！')
                // 部门选择树列表
                this.selectDeptTree()
                // 重新加载表格数据
                this.getList()
              } else {
                this.msgError(resp.message)
              }
            })
          })
          .catch(() => {})
      }
    },

    /** 人员兼职部门方法 start */
    // 人员兼职部门
    handleUserDept() {
      // 获取选中行的id
      const child = this.multipleSelection
      const { userId, userName } = child[0]
      this.$router.push({
        path: '/system/userPartDept',
        name: '人员兼职部门',
        query: { userId, userName }
      })
    },
    // 人员分配菜单和数据权限
    handleMenuAndScope() {
      // 获取选中行的id
      const child = this.multipleSelection
      this.userMenuDataVisible = true
      const userId = child[0].userId
      this.$nextTick(() => {
        this.$refs.userMenuData.showView(userId)
      })
    }
  }
}
</script>
